package org.flik.client.login;

import org.flik.client.login.service.LoginServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginScreen extends Composite {

	private static LoginScreenUiBinder uiBinder = GWT.create(LoginScreenUiBinder.class);

	interface LoginScreenUiBinder extends UiBinder<Widget, LoginScreen> {
	}

	@UiField
	TextBox login, password;
	
	@UiField
	Button submit;
	
	@UiField
	Label errorMsg; 
	
	@UiField
	Label newAccount; 
	
	private DialogBox dialogBox;
	private NewAccountScreen newAccountScreen; 
	
	@UiHandler("newAccount")
	void onNewAccountClick(ClickEvent clickEvent){
		if (dialogBox == null)
			initDialogBox();
		dialogBox.show();
		newAccountScreen.reset();
		dialogBox.center();
	}
	
	private void initDialogBox() {
		dialogBox = new DialogBox(false, true);
		dialogBox.setText("Create new account");
		newAccountScreen = new NewAccountScreen();
		newAccountScreen.addCancelButtonClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		dialogBox.setWidget(newAccountScreen);
		
	}

	@UiHandler({"login", "password"})
	void onEnterPress(KeyPressEvent keyPressEvent){
		if (keyPressEvent.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
			onSubmitClick(null);
	}
	
	@UiHandler("submit")
	void onSubmitClick(ClickEvent clickEvent){
		errorMsg.setVisible(false);
		
		LoginServiceAsync.INSTANCE.login(login.getValue(), password.getValue(), new AsyncCallback<Boolean>() {
			
			@Override
			public void onSuccess(Boolean result) {
				if (result.booleanValue())
					Window.Location.replace("/flik/main.jsp?gwt.codesvr=127.0.0.1:9997");
				else 
					errorMsg.setVisible(true);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());
			}
		});
	
	}
	
	public LoginScreen() {
		initWidget(uiBinder.createAndBindUi(this));
	}

}
